class TableComponent {
    constructor(containerSelector) {
        this.container = document.querySelector(containerSelector);
        // Read editable attribute, default to false
        this.editable = this.container.getAttribute('editable') !== 'false' && 
                       this.container.hasAttribute('editable');
        this.columns = [];
        this.data = [];
        this.editingRowIndex = -1; // Track which row is being edited
        this.init();
    }

    init() {
        this.scanColumns();
        this.render();
    }

    scanColumns() {
        const columnElements = this.container.querySelectorAll('column');
        this.columns = Array.from(columnElements).map(column => {
            const columnConfig = {
                field: column.getAttribute('field'),
                title: column.getAttribute('title') || column.getAttribute('field'),
                width: column.getAttribute('width'),
                sort: column.getAttribute('sort') === 'true'
            };

            // 如果column标签内有内容，将其作为模板处理函数
            if (column.innerHTML.trim()) {
                columnConfig.template = column.innerHTML;
            }

            return columnConfig;
        });
    }

    render() {
        // 创建表格容器
        const tableWrapper = document.createElement('div');
        tableWrapper.className = 'custom-table-wrapper';

        // 创建表格
        const table = document.createElement('table');
        table.className = 'custom-table'; // Changed to custom-table to match CSS

        // 创建表头
        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');

        this.columns.forEach(column => {
            const th = document.createElement('th');
            th.textContent = column.title;
            if (column.width) {
                th.style.width = column.width;
            }
            headerRow.appendChild(th);
        });

        thead.appendChild(headerRow);
        table.appendChild(thead);

        // 创建表体
        const tbody = document.createElement('tbody');
        tbody.id = 'table-body';
        table.appendChild(tbody);

        tableWrapper.appendChild(table);
        this.container.innerHTML = '';
        this.container.appendChild(tableWrapper);

        // 如果有数据则渲染数据
        if (this.data.length > 0) {
            this.renderData();
        }
    }

    renderData() {
        const tbody = this.container.querySelector('#table-body');
        tbody.innerHTML = '';

        this.data.forEach((row, index) => {
            const tr = document.createElement('tr');
            tr.dataset.index = index; // Store row index for reference

            this.columns.forEach(column => {
                const td = document.createElement('td');
                this.renderCell(td, row, index, column);
                tr.appendChild(td);
            });

            tbody.appendChild(tr);
        });
    }

    renderCell(td, row, index, column) {
        console.log(row, index, column, this.editingRowIndex, column.template)

        // If table is not editable, disable all editing features
        if (!this.editable) {
            td.textContent = row[column.field] || '';
            if (column.template) {
                let content = column.template;
                // 传入$index时，获取行索引
                const regex = new RegExp('{{\\$index}}', 'g');
                content = content.replace(regex, index);

                Object.keys(row).forEach(key => {
                    const regex = new RegExp(`{{${key}}}`, 'g');
                    content = content.replace(regex, row[key]);
                });
                td.innerHTML = content;
            }
            return td;
        }

        if (column.template && this.editingRowIndex !== index) {
            // 简单的模板替换，实际项目中可能需要更复杂的模板引擎
            let content = column.template;
            // 传入$index时，获取行索引
            const regex = new RegExp('{{\\$index}}', 'g');
            content = content.replace(regex, index);

            Object.keys(row).forEach(key => {
                const regex = new RegExp(`{{${key}}}`, 'g');
                content = content.replace(regex, row[key]);

            });
            td.innerHTML = content;
            // 如果column.field不为空，那么也可以进行编辑。
            if (column.field) {
                td.addEventListener('dblclick', () => {
                    this.editCell(index, column, td);
                });
            }
        } else if (this.editingRowIndex === index) {
            // Create input for editable fields
            const input = document.createElement('input');
            input.type = 'text';
            input.value = row[column.field] || '';
            input.dataset.field = column.field;
            input.className = 'edit-input';
            input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    this.saveRow(index);
                }
            });
            input.addEventListener('blur', () => {
                // Use a timeout to allow focus event to register on another input
                setTimeout(() => {
                    // Check if the currently focused element is an input
                    console.log(document.activeElement.tagName)
                    if (document.activeElement.tagName !== 'INPUT') {
                        this.saveRow(index);
                    }
                }, 0);
            });
            td.appendChild(input);
            // }
        } else {
            td.textContent = row[column.field] || '';
            // Add click event to make cell editable
            td.addEventListener('dblclick', () => {
                this.editCell(index, column, td);
            });
        }

        return td;
    }

    loadData(url) {
        fetch(url)
            .then(response => response.json())
            .then(data => {
                this.data = data;
                this.renderData();
            })
            .catch(error => {
                console.error('Error loading data:', error);
            });
    }

    // 新增方法：进入编辑模式
    editRow(index) {
        // If table is not editable, do nothing
        if (!this.editable) return;
        
        if (index >= 0 && index < this.data.length) {
            this.editingRowIndex = index;
            this.renderData();

            // Focus first input field
            setTimeout(() => {
                const firstInput = this.container.querySelector('.edit-input');
                if (firstInput) {
                    firstInput.focus();
                    firstInput.select();
                }
            }, 0);
        }
    }

    // 新增方法：编辑单个单元格
    editCell(rowIndex, column, cellElement) {
        // If table is not editable, do nothing
        if (!this.editable) return;
        
        const field = column.field;
        // Create input for cell editing
        const input = document.createElement('input');
        input.type = 'text';
        input.value = this.data[rowIndex][field] || '';
        input.className = 'edit-input';

        // Save on Enter key
        input.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                this.data[rowIndex][field] = input.value;
                // cellElement.textContent = '';
                this.renderCell(cellElement, this.data[rowIndex], rowIndex, column);
            }
        });

        // Save on blur (optional)
        input.addEventListener('blur', () => {
            this.data[rowIndex][field] = input.value;
            // cellElement.textContent = '';
            // this.renderData();
            this.renderCell(cellElement, this.data[rowIndex], rowIndex, column);
        });

        // Clear cell content and add input
        cellElement.innerHTML = '';
        cellElement.appendChild(input);

        // Focus and select input content
        input.focus();
        input.select();
    }

    // 新增方法：取消编辑
    cancelEdit() {
        this.editingRowIndex = -1;
        this.renderData();
    }

    // 新增方法：添加新行
    addNewRow(initialData = {}) {
        // If table is not editable, do nothing
        if (!this.editable) return;
        
        // Create a new row with default values or provided initial data
        const newRow = {};

        // Initialize with default empty values for all fields
        this.columns.forEach(column => {
            if (column.field) {
                newRow[column.field] = initialData[column.field] || '';
            }
        });

        // Add the new row to the data array
        this.data.push(newRow);

        // Enter edit mode for the new row
        this.editRow(this.data.length - 1);
    }

    // 获取列配置的JSON表示
    getColumnsAsJson() {
        return JSON.stringify(this.columns, null, 2);
    }

    // 新增方法：保存编辑的行
    saveRow(index) {
        // If table is not editable, do nothing
        if (!this.editable) return;
        
        if (index >= 0 && index < this.data.length) {
            const inputs = this.container.querySelectorAll('.edit-input');
            inputs.forEach(input => {
                const field = input.dataset.field;
                if (field) {
                    this.data[index][field] = input.value;
                }
            });

            this.editingRowIndex = -1;
            this.renderData();
        }
    }

    // 新增方法：取消编辑
    cancelEdit() {
        this.editingRowIndex = -1;
        this.renderData();
    }

    // 获取列配置的JSON表示
    getColumnsAsJson() {
        return JSON.stringify(this.columns, null, 2);
    }

    // 获取列配置的JavaScript对象
    getColumns() {
        return this.columns;
    }
}

// 导出类以供使用
// 如果在浏览器环境中，将其添加到全局对象
if (typeof window !== 'undefined') {
    window.TableComponent = TableComponent;
}